$(function() {
	App.ctx = '/weixin';
	App.page = '#';
	App.scheme = 'basic';
	App.main = $('#main');
	
	var page = $('body'), 
	hdD = page.children('.headBar'), 
	bdD = $('#main'), 
	lgD = hdD.children('.logon');
	
	function login() {
		App.open({
			ctx : 'base',
			action: 'login',
			title: '用户登录',
			model: true,
			noCloser: true,
			params: { type: 1 }
		}, function(uo, w) {
			init(uo, w);
		});
	}

	App.go = function(to) {
		if (!App.logon) {
			login();
			return;
		}
		App.page = to;
		if (window.location.hash != to) {
			window.location.hash = to;
		}
		var i = to.indexOf('?');
		if (i > 0) {
			to = to.substr(0, i);
		}
		switch (to) {
		case '':
		case '#':
		case '#dir':
			App.show({
				ctx : 'wechat',
				action: 'home'
			}, $.noop, bdD);
			break;
		}
	}

	function adjust() {
		var de = document.documentElement, 
		ch = de.clientHeight, 
		cw = de.clientWidth;
		hdD.width();
		bdD.width(cw).height(ch - hdD.height());
	}
	
	if (window.history && window.history.pushState) {
		window.onpopstate = function() {
			if (App.page != window.location.hash) {
				App.go(window.location.hash);
			}
		}
	}

	hdD.find('span.a[name]').click(function() {
		var a = $(this).attr('name');
		switch(a){
		case 'login':
			login();
			break;
		case 'logout':
			var w = mac.wait('Logout...');
			$.get(App.ctx + '/sys/user/logout.do', {
			}, function(){
				delete App.logon;
				lgD.seek('reg').show();
				lgD.seek('login').show();
				lgD.seek('password').hide();
				lgD.seek('logout').hide();
				lgD.seek('name').empty().hide();
				App.go('#');
				w.close();
			});
			break;
		case 'password':
			App.open({
				ctx : 'base',
				action: 'setpwd',
				model: true,
				
			}, function() {
				
			});
			break;
		}
	});
	
	page.find('nav a').click(function () {
		var action = $(this).attr('name');
		App.show({
			ctx : 'wechat',
			action : action
		}, $.noop, bdD);
	});
	
	function init(uo, w) {
		App.logon = uo;
		App.logon.power = function (t){
			var fa = uo.funcs;
			for (var i in fa){ 
				if (fa[i].code == t) {
					return true;
				}
			}
		}
		
		lgD.seek("test").show();
		lgD.seek('name').text('当前用户：' + App.logon.name).show();
		lgD.seek('reg').hide();
		lgD.seek('login').hide();
		lgD.seek('logout').show();
		lgD.seek('password').show();
		
		if (App.page != window.location.hash) {
			console.log("current: " + window.location.hash);
			App.go(window.location.hash);
		}
		if (w) {
			w.close();
		}
	}

	if (!App.logon && $.cookie('token')) {
		var w = mac.wait('Loading...')
		$.post(App.ctx + '/sys/power/check.do', {
			r: Math.random()
		}, function(rs){
			var ro = mac.eval(rs);
			if (ro.success) {
				init(uo, w);
			} else {
				w.close();
				alert('认证信息已过期');
				login();
			}
		});
	} else {
		login();
	}
});
